package com.example.myapplication;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.myapplication.utils.EncodingUtils;
import com.example.myapplication.utils.OkhttpHelper;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ThirdActivity extends AppCompatActivity {
    private ImageView enCodeImage2;//展示生成的二维码
    private TextView txt; //定义文本视图组件
    private Gson gson;
    private String mUuid;
    private String userId;
    private Timer  timer;
    private Button btn2;
    private ProgressBar progressBar;
    private int mProgressBar=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third);
        //初始化控件
        enCodeImage2 = (ImageView) findViewById(R.id.code_image2);
        btn2 = (Button)findViewById(R.id.Button01);
        progressBar = (ProgressBar)findViewById(R.id.progressBar);

        txt = (TextView)findViewById(R.id.textview1);
        gson = new Gson(); //实例化对象

        getRequest();  //get请求获取到接口中的数据
        //创建一个计时器
        timer = new Timer();
        process();

    }
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            initStatus();
        }
    };

    //get请求方式的实现   从后台访问给定接口的uuid
    private void getRequest(){
        //get请求
        String url = "http://fota.ff255.cn/frontuser/frontapi/appUser/getQRCodeValue";
        OkhttpHelper.getRequest(url, new Callback() { //回调函数
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("11111111111", "onFaiure：" + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                TestBean testBean = gson.fromJson(response.body().string(), TestBean.class);
                //获取到后台数据的tag和values （标志位、uuid用于使用id）
                Log.d("111111111", "on Response:" + testBean.getData().getTag());
                Log.d("222222222", "on Response1: " + testBean.getData().getValue());
                mUuid  = testBean.getData().getValue(); //uuid的数值
                // 子线程中创建一个Message对象，为了携带子线程中获取到的数据给主线程
                Message message = new Message();
                //将获取到数据封装到msg中
                message.obj= "tag:" + testBean.getData().getTag() + ";uuid:" + testBean.getData().getValue()+";";
                //使用handler对象将message发送到主线程
                message.what = 5; //数据请求成功，后面生成一个二维码的过程
                handler.sendMessage(message);
            }
        });
    }

    //在主线程中创建一个Handler对象
    Handler handler = new Handler() {
        @Override
        //重写handler的handleMessage方法，用来接收子线程中发来的消息
        public void handleMessage(@NonNull final Message msg) {
            super.handleMessage(msg);
            if(msg .what == 0x110){
                //Toast.makeText(MainActivity.this, "加载成功", Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.GONE);
                enCodeImage2.setVisibility(View.VISIBLE);
                Toast.makeText(ThirdActivity.this, "数据加载完成", Toast.LENGTH_SHORT).show();
            }

            switch (msg.what){

                case 0://数据请求成功
                    txt.setText("请使用手机APP扫描二维码绑定账号");break;
                case 1://表示手机端扫码成功，并且用户点击同意登录
                    show();
                    txt.setText("飞歌185096");
                    btn2.setVisibility(View.VISIBLE);
                    btn2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(btn2 == v) {
                                Intent intent1 = new Intent(ThirdActivity.this, MainActivity.class);
                                startActivity(intent1);
                            }
                        }
                    });
                    break;

                case 2://表示手机端扫码成功，但是用户点击拒绝
                    enCodeImage2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(enCodeImage2 == v) {
                                Intent intent = new Intent(ThirdActivity.this, SecondActivity.class);
                                startActivity(intent);
                            }
                        }
                    });
                    txt.setText("您已取消绑定账号您可再次扫码绑定账号");break;
                case 3://表示手机端扫码成功，用户还没有点击同意或者拒绝
                    enCodeImage2.setBackgroundColor(Color.GRAY);
                    txt.setText("扫描成功请在APP中点击确认"); break;
                case 4://表示uuid已经过期，重新获取
                    getRequest();
                    txt.setText("验证码失效，重新登录");break;
                case 5://生成一个二维码的标志
                    show((String) msg.obj);
                    timer.schedule(task,0,3000);break;
                default:
                    break;
            }
        }
    };

    //生成二维码的功能操作，直接获取到接口（uuid）json字符串转化为对应的二维码，并且输出显示
    public void show(String str)
    {
        //R.drawable.logo为logo图片

        // Toast.makeText(this, "请使用手机扫码登录车机账号", Toast.LENGTH_SHORT).show();
        //加载图片源（路径）
        Bitmap logoBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.logo);
        //生成二维码
        Bitmap codeBitmap = EncodingUtils.createQRCode(str,500,500,logoBitmap);
        enCodeImage2.setImageBitmap(codeBitmap);//显示二维码
    }

    //循环定时检测接口的状态  mUuid在第一部获取到的数据mUuid
    public void initStatus()
    {
        //判断接口状态的接口
        String url = "http://fota.ff255.cn/frontuser/frontapi/appUser/getSweepCodeLoginStatus//"+mUuid;
        Log.d("123", " initStatus mUuid:" + mUuid);
        OkhttpHelper.getRequest(url, new Callback() {
            @Override
            //请求失败
            public void onFailure(Call call, IOException e) {
                Log.d("123", "onFailure:" + e.getMessage());
            }
            @Override
            //请求成功
            public void onResponse(Call call, Response response) throws IOException {
                final Message msg = new Message();
                //处理状态为欸400002时候，response数据解析，或如到userId
                ScanCodeStatus codeStatus = gson.fromJson(response.body().string(),ScanCodeStatus.class);
                userId = codeStatus.getData().getUserId();
                Log.d("12345","success:"+codeStatus.getData().getFlag());

                switch (codeStatus.getData().getFlag()){
                    case "200"://数据请求成功
                        msg.what = 0;
                        break;
                    case "40002"://表示手机端扫码成功，并且用户点击同意登录
                        msg.what = 1;
                        break;
                    case "40003"://表示手机端扫码成功，但是用户点击拒绝
                        msg.what = 2;
                        break;
                    case "40004"://表示手机端扫码成功，用户还没有点击同意或者拒绝
                        msg.what = 3;
                        break;
                    case "10005"://表示uuid已经过期，重新获取
                        msg.what = 4;
                        break;
                    default:break;
                }
                handler.sendMessage(msg);
            }
        });
    }

    public void UserGet()
    {
        String url = "http://test.frp.flyaudio.cn/v1/app/user/operate/user/info/fg/"+userId;
        Log.d("12323123","userId:"+userId);

        OkhttpHelper.getRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d("11","failure:"+e.getMessage());
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Log.d("22","success"+response.body().string());
            }
        });
    }

    //显示图片的函数
    public Bitmap getPicture(String path){
        Bitmap bm=null;
        try{
            URL url=new URL(path);
            URLConnection connection=url.openConnection();
            connection.connect();
            InputStream inputStream=connection.getInputStream();
            bm = BitmapFactory.decodeStream(inputStream);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  bm;
    }

    void show()
    {
        //创建了一个主线程，主要用来更新UI界面
        new Thread(new Runnable() {
            @Override
            public void run() {
                String str = "http://cqfg-carinternet.oss-cn-chengdu.aliyuncs.com/fg_1606444073792.png";
                final Bitmap bitmap = getPicture(str);
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                enCodeImage2.post(new Runnable() {
                    @Override
                    public void run() {
                        enCodeImage2.setImageBitmap(bitmap);
                    }
                });
            }
        }).start();
    }
    void process(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    mProgressBar = dowork();//判断进度时间是否到
                    Message m = new Message();
                    if (mProgressBar < 100) {
                        progressBar.setProgress(mProgressBar);
                        handler.sendMessage(m);
                    } else {
                        m.what = 0x110;
                        handler.sendMessage(m);
                        break;
                    }
                }
            }
            private int dowork() {
                mProgressBar += Math.random() * 5;
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return mProgressBar;
            }
        }).start();

    }

}